package com.kc.sjwh.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kc.sjwh.dao.AppDao;
import com.kc.sjwh.dao.JqbzzdDao;
import com.kc.sjwh.dao.JqxzDao;
import com.kc.sjwh.dao.OrganDao;
import com.kc.sjwh.dao.ResDao;
import com.kc.sjwh.dao.RoleDao;
import com.kc.sjwh.dao.SysDao;
import com.kc.sjwh.dao.ZhzxpzDao;
import com.kc.sjwh.dao.ZhzxpzgxhzbDao;
import com.kc.sjwh.dao.ZykzdDao;
import com.kc.sjwh.entity.po.App;
import com.kc.sjwh.entity.po.Jqbzzd;
import com.kc.sjwh.entity.po.Res;
import com.kc.sjwh.entity.po.Role;
import com.kc.sjwh.entity.po.Zhzxpz;
import com.kc.sjwh.entity.po.Zhzxpzgxhzb;
import com.kc.sjwh.entity.po.Zykzd;
import com.kc.sjwh.entity.vo.dict.DictItem;
import com.kc.sjwh.entity.vo.dict.DictType;
import com.kc.sjwh.other.Cfg;
import com.kc.sjwh.other.Dict;
import com.kc.sjwh.other.QueryParam;
import com.kc.sjwh.other.Tool;

/**
 * 系统service
 * @author zhangguihua(hua7381@163.com)
 * date: 2017年7月19日
 */
@Service
public class SysService {
	Logger logger = Logger.getLogger(SysService.class);
	@Autowired
	SysDao sysDao;
	@Autowired
	AppDao appDao;
	@Autowired
	ResDao resDao;
	@Autowired
	RoleDao roleDao;
	@Autowired
	OrganDao organDao;
	@Autowired
	JqxzDao jqxzDao;
	@Autowired
	JqbzzdDao jqbzzdDao;
	@Autowired
	ZykzdDao zykzdDao;
	@Autowired
	ZhzxpzDao zhzxpzDao;
	@Autowired
	ZhzxpzgxhzbDao zhzxpzgxhzbDao;

	public void loadDict() {
		List<DictItem> list = null;

		try {
			list = sysDao.getDict("性别");
			Dict.setSex(new DictType(list, this.listToMap(list)));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		try {
			list = sysDao.getDict("人员职务");
			Dict.setRyzw(new DictType(list, this.listToMap(list)));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		try {
			list = sysDao.getDict("PDT通话组类型");
			Dict.setPdtthzlx(new DictType(list, this.listToMap(list)));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		try {
			list = sysDao.getDict("PDT设备类型");
			Dict.setPdtsblx(new DictType(list, this.listToMap(list)));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		//单位
		try {
			list = sysDao.getOrgans();
			this.figurePid(list, Cfg.getInst().getDwLen(), Cfg.getInst().getDwLevCode());
			Dict.setOrgan(new DictType(list, this.listToMap(list)));
			logger.info("[单位]加载完毕, size="+Dict.getOrgan().getList().size());
		} catch (Exception e) {
			logger.error("[单位]加载失败:"+e.getMessage());
			list = new ArrayList();
			list.add(new DictItem("xxx", "xxx"));
			Dict.setOrgan(new DictType(list, this.listToMap(list)));
		}
		//可选择的单位
		try {
			list = sysDao.getOrgans4Choose();
			this.figurePid(list, Cfg.getInst().getDwLen(), Cfg.getInst().getDwLevCode());
			Dict.setOrgan4Choose(new DictType(list, this.listToMap(list)));
			logger.info("[可选单位]加载完毕, size="+Dict.getOrgan4Choose().getList().size());
		} catch (Exception e) {
			logger.error("[可选单位]加载失败:"+e.getMessage());
			list = new ArrayList();
			list.add(new DictItem("xxx", "xxx"));
			Dict.setOrgan(new DictType(list, this.listToMap(list)));
		}
		
		//警情性质
		try {
			list = sysDao.getJqxzs();
			this.figurePid(list, Cfg.getInst().getJqxzLen(), Cfg.getInst().getJqxzLevCode());
			Dict.setJqxz(new DictType(list, this.listToMap(list)));
			logger.info("[警情性质]加载完毕, size="+Dict.getJqxz().getList().size());
		} catch (Exception e) {
			logger.error("[警情性质]加载失败:"+e.getMessage());
			list = new ArrayList();
			list.add(new DictItem("xxx", "xxx"));
			Dict.setJqxz(new DictType(list, this.listToMap(list)));
		}
	}

	/**
	 * 计算pid(父节点的id)
	 * @param list
	 * @param codeLen 代码的长度
	 * @param levCode 级别代码，如0或00
	 */
	private void figurePid(List<DictItem> list, int codeLen, String levCode) {
		for(DictItem item : list) {//结尾去0
			item.setId(this.rightTrim(item.getId(), levCode));
		}
		
		String id;
		String pid;
		Set<String> pool = new HashSet<String>();//缓存池，用于缓存已遍历到的code
		for(DictItem item : list) {
			id = item.getId();
			//循环递减1位，直到找到相应父节点为止
			pid = id;
			while(!pool.contains(pid) && pid.length()>levCode.length()) {
				pid = pid.substring(0 , pid.length()-levCode.length());
			}
			pool.add(id);
			item.setPid(pid);
		}

		/**/
		for(DictItem item : list) {//结尾补0
			item.setId(Tool.rightPad(item.getId(), codeLen, levCode));
			item.setPid(Tool.rightPad(item.getPid(), codeLen, levCode));
		}
	}
	/**
	 * 向右削减
	 * @param str
	 * @param by
	 * @return
	 */
	private String rightTrim(String str, String by) {
		String res = str;
		while(res.endsWith(by)) {
			res = res.substring(0, res.length()-by.length());
		}
		return res;
	}
	
	/**
	 * list转成map
	 * @param list
	 * @return
	 */
	private Map<String,String> listToMap(List<DictItem> list) {
		Map<String,String> map = new HashMap<String,String>();
		for(DictItem i : list) {
			map.put(i.getId(), i.getName());
		}
		return map;
	}
	
	/**
	 * 取所有应用为字典
	 * @return
	 */
	public List<DictItem> getAllAppAsDict() {
		List<DictItem> list = new ArrayList<DictItem>();
		for(App bean : appDao.getList(new QueryParam().setOrder("mc"))) {
			DictItem di = new DictItem();
			di.setId(bean.getId());
			di.setName(bean.getMc());
			list.add(di);
		}
		return list;
	}

	/**
	 * 取应用下的所有资源为字典
	 * @param yyid 所属应用的id
	 * @return
	 */
	public List<DictItem> getAllResAsDict(String yyid) {
		List<DictItem> list = new ArrayList<DictItem>();
		for(Res bean : resDao.getList(new QueryParam().put("yyid", yyid).setOrder("t.yyid"))) {
			DictItem di = new DictItem();
			di.setId(bean.getId());
			di.setName(bean.getMc());
			di.setPid(bean.getFjid());
			list.add(di);
		}
		return list;
	}
	
	public List<DictItem> getAllJqbzlbDict() {
		List<DictItem> list = new ArrayList<DictItem>();
		List<Jqbzzd> list2 = jqbzzdDao.getList("getBzlx", new QueryParam());
		for(Jqbzzd bean : list2){
			DictItem di = new DictItem();
			di.setId(bean.getBzlxdm());
			di.setName(bean.getBzlxdmms());
			di.setPid("0");
			list.add(di);
		}
		return list;
	}
	
	/**
	 * 资源库字典类别集
	 * @return
	 */
	public List<DictItem> getAllZykzdDict() {
		List<DictItem> list = new ArrayList<DictItem>();
		List<Zykzd> list2 = zykzdDao.getList("getDictType", new QueryParam());
		for(Zykzd bean : list2){
			DictItem di = new DictItem();
			di.setId(bean.getZylx());
			di.setName(bean.getZylxms());
			di.setPid("0");
			list.add(di);
		}
		return list;
	}
	 
	/**
	 * 获得指挥中心
	 * @return
	 */
	 public List<DictItem> getAllZhzxDict () {
			List<DictItem> list = new ArrayList<DictItem>();
			List<Zhzxpz> list2 = zhzxpzDao.getList("getZhzx", new QueryParam());
			for(Zhzxpz bean : list2){
				DictItem di = new DictItem();
				di.setId(bean.getZhzxbh());
				di.setName(bean.getZhzxqmc());
				di.setPid("0");
				list.add(di);
			}
			return list;
		}
	 
	 /**
	  * 获得所有指标项
	  * @return
	  */
	 public List<DictItem> getAllPzxDict () {
			List<DictItem> list = new ArrayList<DictItem>();
			List<Zhzxpz> list2 = zhzxpzDao.getList("getPzx", new QueryParam());
			for(Zhzxpz bean : list2){
				DictItem di = new DictItem();
				di.setId(bean.getZbxbh());
				di.setName(bean.getZbxmc());
				di.setPid("0");
				list.add(di);
			}
			return list;
		}
	 /**
	  * 获得所有指标项
	  * @return
	  */
	 public List<DictItem> getAllZhzxPzxDict () {
		 List<DictItem> list = new ArrayList<DictItem>();
		 List<Zhzxpzgxhzb> list2 = zhzxpzgxhzbDao.getList(new QueryParam());
		 for(Zhzxpzgxhzb bean : list2){
			 DictItem di = new DictItem();
			 di.setId(bean.getZbxbh());
			 di.setName(bean.getZbxmc());
			 list.add(di);
		 }
		 return list;
	 }
	
	/**
	 * 警情标注字典树
	 * @return
	 */
	public List<DictItem> getAllJqbzzdAsDict(String bzbh) {
		List<DictItem> list = new ArrayList<DictItem>();
		QueryParam p = new QueryParam();
		if(null != bzbh && !"".equals(bzbh)){
			p.addSqlCondition(" t.bzbh not in (select tt.bzbh from T_JCJ_JQBZZD tt start with tt.bzbh = '" + 
					bzbh + "' connect by tt.fbzbh = prior tt.bzbh)");
		}
		List<Jqbzzd> list2 = jqbzzdDao.getList(p);
		for(Jqbzzd bean : list2) {
			DictItem di = new DictItem();
			di.setId(bean.getBzbh());
			di.setName(bean.getBzmc());
			di.setPid(bean.getFbzbh());
			list.add(di);
		}
		return list;
	}

	/**
	 * 取所有角色为字典
	 * @return
	 */
	public List<DictItem> getAllRoleAsDict() {
		List<DictItem> list = new ArrayList<DictItem>();
		for(Role bean : roleDao.getList(new QueryParam().setOrder("t.yyid"))) {
			DictItem di = new DictItem();
			di.setId(bean.getId());
			di.setName(bean.getMc());
			list.add(di);
		}
		return list;
	}

	public String loadMenusHtml(String userId) {
		List<Res> menus = null;
		if("admin".equals(userId)) {
			menus = resDao.getMenusByAppCode(Cfg.getInst().getAppCode());
		} else {
			menus = resDao.getMenus4User(Cfg.getInst().getAppCode(), userId);
		}
		return Tool.menusToHtml(menus);
	}
	
	/**
	 * 根据类别取字典
	 * @return
	 */
	public List<DictItem>  getDictByType(String zdlb) {
		return sysDao.getDict(zdlb);
	}
	
	/**
	 * 取终端所属组为字典
	 * @return
	 */
	public List<DictItem> getAllZdsszAsDict() {
		return sysDao.getList("getZdz",new QueryParam());
	}

	/**
	 * 取工作台组为字典
	 * @return
	 */
	public List<DictItem> getAllGztzAsDict() {
		return sysDao.getList("getGztz",new QueryParam());
	}

	/**
	 * 取指挥中心为字典
	 * @return
	 */
	public List<DictItem> getAllZhzxAsDict() {
		return sysDao.getList("getZhzx",new QueryParam());
	}

	/**
	 * 取工作台配置项
	 * @return
	 */
	public List<DictItem> getAllGztpzxAsDict() {
		return sysDao.getList("getGztpzx",new QueryParam());
	}
	/**
	 * 取内部单位
	 * @return
	 */
	public List<DictItem> getAllNbdwAsDict() {
		return sysDao.getList("getOrgans_nb",new QueryParam());
	}
}
